import axios from 'axios'
// import {
//   Notify,
//   Toast
// } from 'vant'
import {Message} from 'element-ui'
 import cfg from '@/config'
// import {
//   addPending,
//   removePending
// } from '@/utils/padding'
// import {
//   LreItem,
//   LgetItem
// } from '@/utils/storage'
import {
  LgetItem,
  LreItem
} from '@/utils/storage'

import store from '@/store'

axios.defaults.baseURL = `${cfg.host}${cfg.port}${cfg.baseUrl}`
// axios.defaults.baseURL=`${config.host}${config.port}${config.baseUrl}`;
// axios.defaults.baseURL='';
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.headers.get['Accept'] = 'application/json'
axios.defaults.timeout = 20000
axios.defaults.withCredentials = true
let ajaxTimes = 0

export function startLoading() {
  if (ajaxTimes === 0) {
    store.commit('status/SET_LOADING',true)
  }
  ajaxTimes++
}
export function closeLoading() {
  if (ajaxTimes <= 0) return
  ajaxTimes--
  if (ajaxTimes === 0) {
    store.commit('status/SET_LOADING',false)
    ajaxTimes = 0
  }
}

axios.interceptors.request.use(
  config => {
    startLoading()
    LgetItem('jwtToken') && (config.headers['Token'] = LgetItem('jwtToken'))
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

axios.interceptors.response.use(res => {
  closeLoading()
  const data = res.data;
  const status = res.status;
  // 响应拦截
  if (status == 200) {
    if (data) {
      const serveCode = data.code;
      if (serveCode === 0) {
        return Promise.resolve(data.data);
      } else {
        if (serveCode == -1) {
          Message({
            type:'error',
            message:data.desc,
            duration: 1000,
          })
          return Promise.reject(data);
        }
      }
    }
  } else {
    Message({
      type:'error',
      message:res.desc,
      duration: 1000,
    })
    return Promise.reject(data);
  }
}, err => {
  closeLoading()
  console.log(err.response)
  if(err.response.status == 401){//token，"Unauthorized"
    LreItem('jwtToken')
    Message({
      type:'error',
      message:'登录已过期',
      duration: 1000,
      onClose:()=>{
        window.location.reload()
      }
    })
  }
  return Promise.reject(err)
})

export default function (options) {
  let params = {
    method: options.method,
    url: options.url,
    data: options.params,
    requestMessage: true,
    requestSame: 'throttle',
    ...options.other
  }
  if (params.method.toLowerCase() === 'get') {
    params.params = params.data
    delete params.data
  }
  return axios(params)
}